package com.demo.exchange_topic;

import com.demo.commons.MqCons;
import com.demo.commons.message.LogMessage;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author shenguangyang
 */
@Component
@RabbitListener(bindings = {
        @QueueBinding(value = @Queue(value = MqCons.LOG_ERROR_QUEUE), key = MqCons.LOG_ERROR_ROUTING_KEY,
                exchange = @Exchange(value = MqCons.LOG_EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class LogErrorListener {

    @RabbitHandler
    public void onMessage(LogMessage msg, Channel channel, Message message) {
        try {
            System.out.println("log error message: " + msg);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                // channel.basicRecover(true);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
